package com.niiwoo.civet.trade.service.local.contract;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.trade.dao.entity.FadadaContractTemplateFile;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectContract;
import com.niiwoo.civet.trade.enums.BorrowerTypeEnum;
import com.niiwoo.civet.trade.service.local.contract.vo.CreditEnquiryAuthorizationDTO;
import com.niiwoo.civet.user.dto.request.SimpleOrgInfo;
import com.niiwoo.civet.user.dto.response.UserAuthorizationInfoResponseDTO;
import com.niiwoo.civet.user.dto.response.UserIdentityInfoResponseDTO;
import com.niiwoo.civet.user.service.OrganizationDubboService;
import com.niiwoo.civet.user.service.UserAuthorizationInfoDubboService;
import com.niiwoo.civet.user.service.UserIdentityDubboService;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.fadada.dto.request.GenerateContractRequestDTO;
import com.niiwoo.tripod.fadada.dto.response.FadadaResponseDTO;
import com.niiwoo.tripod.fadada.enums.SignClientRoleEnum;
import com.niiwoo.tripod.provider.exception.BizException;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 征信查询授权书
 * 
 * @author liaojunjun
 *
 */
@Service
public class CreditEnquiryAuthorizationContract extends AbstractFadadaContract {

	private static final Logger logger = LoggerFactory.getLogger(CreditEnquiryAuthorizationContract.class);

	@Autowired
	private SnowflakeIdWorker snowflakeIdWorker;
	@Autowired
	private PrivacyMasks privacyMasks;

	@Reference(version = "1.0.0")
	private UserAuthorizationInfoDubboService userAuthorizationInfoDubboService;
	@Reference(version = "1.0.0")
    private OrganizationDubboService organizationDubboService;
	@Reference(version = "1.0.0")
	private UserIdentityDubboService userIdentityDubboService;

	@Override
	public ProjectContract contractHandler(FadadaContractTemplateFile contractTemplate, String bizContractNo,
			Project project, String userId) throws Exception {
		logger.info("征信查询授权书处理开始... projectId:{}", project.getProjectId());
		String contractId = snowflakeIdWorker.nextId() + "";

		CreditEnquiryAuthorizationDTO creditEnquiryDTO = new CreditEnquiryAuthorizationDTO();
		creditEnquiryDTO.setContractId(contractId);

		if(BorrowerTypeEnum.PERSONAL.getType().equals(project.getBorrowerType())){
			UserIdentityInfoResponseDTO userIdentityInfo = userIdentityDubboService.get(project.getBorrowUserId());
			if (userIdentityInfo == null){
				throw new BizException("TRD10005", "征信查询授权书处理异常 userIdentityInfo is null");
			}
			creditEnquiryDTO.setIdCard(userIdentityInfo.getIdCard());
			creditEnquiryDTO.setUserName(userIdentityInfo.getName());
			UserAuthorizationInfoResponseDTO userAuthorizationInfo = userAuthorizationInfoDubboService.getUserAuthorizationInfo(project.getBorrowUserId());
			creditEnquiryDTO.setFadadaCacertId(userAuthorizationInfo.getFadadaCacertId()); // 授权信息(CA证书编号)
		} else { //企业
			SimpleOrgInfo orgInfo = organizationDubboService.getByOrgId(project.getBorrowUserId());
			if(orgInfo == null){
				throw new BizException("TRD10005", "征信查询授权书处理异常 orgInfo is null");
			}
			creditEnquiryDTO.setIdCard(StringUtils.isBlank(orgInfo.getUnifiedSocialCreditCode())
					? orgInfo.getCharterCode()
					: orgInfo.getUnifiedSocialCreditCode()); // 统一社会信用代码，如果统一社会信用代码为空则取用营业执照编号
			creditEnquiryDTO.setUserName(orgInfo.getOrganizationName());
			creditEnquiryDTO.setFadadaCacertId(orgInfo.getFadadaCacertId()); // 法大大证书ID 授权信息(CA证书编号)
		}

		this.generateContract(contractTemplate, creditEnquiryDTO);

		ProjectContract result = this.signContract(contractTemplate, creditEnquiryDTO);

		this.contractFilling(creditEnquiryDTO.getContractId());
		logger.info("征信查询授权书处理结束... projectId:{}", project.getProjectId());
		return result;
	}

	private void generateContract(FadadaContractTemplateFile contractTemplate, CreditEnquiryAuthorizationDTO creditEnquiryDTO) throws Exception {
		logger.info("征信查询授权书生成开始... projectId:{}", creditEnquiryDTO.getProjectId());

		GenerateContractRequestDTO dto = new GenerateContractRequestDTO();

		dto.setContractId(creditEnquiryDTO.getContractId());
		dto.setDocTitle(contractTemplate.getTemplateName());
		dto.setTemplateId(contractTemplate.getTemplateId());

		Map<String, String> parameterMap = new HashMap<String, String>();

		parameterMap.put("consignor", creditEnquiryDTO.getUserName());
		parameterMap.put("idCard", privacyMasks.maskIdCardSixTwo(creditEnquiryDTO.getIdCard()));
		parameterMap.put("signDate", DateFormatUtils.format(new Date(), "yyyy年MM月dd日"));
		dto.setParameterMap(parameterMap);

		generateContract(dto);
		logger.info("征信查询授权书生成结束... projectId:{}", creditEnquiryDTO.getProjectId());
	}

	private ProjectContract signContract(FadadaContractTemplateFile contractTemplate, CreditEnquiryAuthorizationDTO creditEnquiryDTO) throws Exception {
		String METHOD_NAME = "法大大合同自动签署-征信查询授权书 projectId:" + creditEnquiryDTO.getProjectId();
		logger.info(METHOD_NAME);

		String docTitle = creditEnquiryDTO.getUserName() + "的征信查询授权书_" + creditEnquiryDTO.getContractId();

		// 投资人签署
		String transactionId = snowflakeIdWorker.nextId() + "";
		String borrowerCaCertId = creditEnquiryDTO.getFadadaCacertId();
		String borrowerSignKeyword = creditEnquiryDTO.getUserName();
		FadadaResponseDTO fadadaResponse = extSignAuto(transactionId, creditEnquiryDTO.getContractId(), borrowerCaCertId,
				SignClientRoleEnum.BORROWER.getValue(), docTitle, borrowerSignKeyword);
		logger.info("法大大合同自动签署-征信查询授权书 投资人签署结束... projectId:{}", creditEnquiryDTO.getProjectId());
		return this.buildContractUpdateRecord(contractTemplate.getTemplateId(), creditEnquiryDTO.getContractId(), transactionId,
				fadadaResponse.getViewUrl(), fadadaResponse.getDownloadUrl());
	}

}
